<?php
/**
 * User: xialei
 * Date: 2016/7/2 0002
 * Time: 15:25
 */

namespace app\modules\admin\controllers;


use app\commands\CommonTool;
use app\models\News;
use yii\base\UserException;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;

class NewsController extends Controller
{
    public function actionAll()
    {
        return News::find()->asArray()->all();
    }

    /**
     * 添加|编辑
     * @param int $id
     * @return News|null|static
     * @throws NotFoundHttpException
     * @throws UserException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionPost($id = 0)
    {
        if ($id > 0) {
            $news = News::findOne($id);
            if (empty($news)) {
                throw new NotFoundHttpException('文章不存在');
            }
        } else {
            $news = new News();
        }
        $news->setAttributes(\Yii::$app->request->getBodyParams());
        if (!$news->save()) {
            throw new UserException(CommonTool::getFirstError($news));
        }
        return $news;
    }

    /**
     * 查看文章
     * @param $id
     * @return null|static
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        $news = News::findOne($id);
        if (empty($news)) {
            throw new NotFoundHttpException('文章不存在');
        }
        return $news;
    }
}